package com.example.pmxt.modules.region;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.example.pmxt.common.BaseService;
import com.example.pmxt.domain.Region;
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
@Transactional
public class RegionService extends BaseService<RegionMapper,Region> {

    private RegionMapper mapper;

    @Autowired
    public RegionService(RegionMapper mapper) {
        this.mapper = mapper;
    }


    @SneakyThrows
    public boolean importFileToDB(boolean deleteHistory, MultipartFile file) {
    //是否删除数据库表中历史数据
        if (deleteHistory) {
            this.remove(null);
        }
    //读取excel表格中数据
        EasyExcel.read(file.getInputStream(), Region.class, new ReadListener<Region>() {
            //定义一个常量BATCH_SIZE与一个列表ls
            private static final int BATCH_SIZE = 1000;
            private List<Region> ls = Lists.newArrayList();
            //重写invoke方法
            @Override
            public void invoke(Region data, AnalysisContext context) {
                //System.err.println(data);
                //列表里添加Flowfee类的数据
                ls.add(data);
                //每1000条放到数据库里面
                if (ls.size() >= BATCH_SIZE) {
                    RegionService.this.saveBatch(ls);
                    ls.clear();
                }
            }
            //重写doAfterAllAnalysed方法，处理剩下的数据，例如1050条，其中1000条在上面已经放到数据库，剩下的50条下面处理
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                RegionService.this.saveBatch(ls);
            }
        }).sheet().doRead();
        return true;
    }

}
